package com.chtw.edu.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chtw.edu.bean.User;
import com.chtw.edu.service.impl.UserServiceImpl;
import com.chtw.edu.utils.response.RespUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author chtw
 * @date 2020-10-11 17:18
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping(value = "/authentication")
    public RespUtils<User> authentication(@RequestBody User user, HttpSession session) {
        try {
            return RespUtils.success(userService.authentication(user, session));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail("认证失败！");
        }
    }

    @GetMapping(value = "/info")
    public RespUtils<User> info(HttpSession session) {
        String token = session.getAttribute("token").toString();
        DecodedJWT jwt = JWT.decode(token);
        String userName = jwt.getClaim("loginName").asString();
        User user = new User();
        user.setToken(token);
        user.setUserName(userName);
        return RespUtils.success(user);
    }
}
